import { z } from "zod";
import sharp from 'sharp';
import fs from 'fs';
import { tmpNameSync } from 'tmp';
import { getFileBuffer, uploadPngFileByBuffer } from "../../../service/oss.js";
import { logger } from '../../../tools/index.js';

export default {
    api: "chinese-new-interpretation",
    name: "汉语新解",
    description: "汉语新解插件-可以对词组进行新的解释",
    requestSchema: z.object({
        input: z.string().describe("待解释名词"),
    }),
    func: async ({ input }, context) => {
        try {
            const file = await loadFileNameAndBuffer(input);
            context.files.push({
                name: file.name,
                buffer: file.buffer
            });
            context.doNotTalk = true;
            return `汉语新解精美卡片已经发送，请在${context.terminal}查收，文件名称为 ${file.name}`;
        } catch (err) {
            return `系统错误，错误信息: ${err}`;
        }
    }
}

const loadFileNameAndBuffer = async (input) => {
    const fileName = `${input}_${Math.floor(Math.random() * 10) + 1}.png`;
    const fileKey = `chinese-new-interpretation/${fileName}`;
    const fileBuffer = await getFileBuffer(fileKey);
    if (fileBuffer) {
        return {
            name: fileName,
            buffer: fileBuffer
        };;
    }

    const res = await fetch("https://texthuman.ai/api/chat", {
        "headers": {
            "accept": "*/*",
            "accept-language": "zh-CN,zh-TW;q=0.9,zh;q=0.8,en-US;q=0.7,en;q=0.6",
            "content-type": "application/json",
            "priority": "u=1, i",
            "sec-ch-ua": "\"Google Chrome\";v=\"129\", \"Not=A?Brand\";v=\"8\", \"Chromium\";v=\"129\"",
            "sec-ch-ua-mobile": "?0",
            "sec-ch-ua-platform": "\"Windows\"",
            "sec-fetch-dest": "empty",
            "sec-fetch-mode": "cors",
            "sec-fetch-site": "same-origin",
            "Referer": "https://texthuman.ai/",
            "Referrer-Policy": "strict-origin-when-cross-origin"
        },
        "body": JSON.stringify({ prompt: input }),
        "method": "POST"
    });

    if (res.ok) {
        const resText = await res.text();
        const resp = JSON.parse(resText);
        const svgString = resp.svgContent;

        // 使用svg2img将SVG字符串转换为Buffer，这里以PNG格式为例
        const pngBuffer = await convertSvg2ImgBuffer(svgString);
        if (!pngBuffer) {
            throw new Error("生成svg图片失败");
        }

        const fileUrl = await uploadPngFileByBuffer(fileKey, pngBuffer);
        logger.info("汉语新解图片链接：", fileUrl);
        return {
            name: fileName,
            buffer: pngBuffer
        };
    } else {
        throw new Error("服务器异常");
    }
}

async function convertSvg2ImgBuffer(svgString) {
    return new Promise((resolve, reject) => {
        // 创建一个临时SVG文件
        const tmpFile = tmpNameSync({ postfix: '.svg' });
        fs.writeFileSync(tmpFile, svgString);

        // 使用sharp转换SVG为PNG
        sharp(tmpFile)
            .resize({ width: 800, height: 600, fit: 'outside' })
            .png({
                quality: 100,
                compressionLevel: 0,
            }) // 设置PNG质量为100
            .toBuffer()
            .then(buffer => {
                // 成功获取Buffer，删除临时文件
                fs.unlinkSync(tmpFile);
                resolve(buffer);
            })
            .catch(err => {
                // 出错时删除临时文件
                fs.unlinkSync(tmpFile);
                reject(err);
            });
    })
};